#!/usr/bin/env python
# coding=utf-8

from vavava import util
from .. import fetcherbase,track_db
from datetime import datetime,timedelta

class fetcher_dhl(fetcherbase.FetcherBase):
    def __init__( self, item_id, log ):
        fetcherbase.FetcherBase.__init__( self, item_id=item_id, track_type=fetcherbase.TRACK_TYPE_DHL, log=log )
        self.fetch_url = r'http://www.dhl.com.au/content/au/en/express/tracking.shtml?brand=DHL&AWB=%s'\
              % self.item_id
        self.reg_str_1      = r'(?<=<THEAD>)(?P<list>.+?)((?=<THEAD>)|(?=$))'
        self.reg_str_date   = r'<tr>\s*<th[^>]*.(?P<data>[^<]*)</th>'
        self.reg_str_tbodys = r'(?<=<tbody>)(?P<tbodys>.*?)(?=</tbody>)'
        self.reg_str__info  = r'<TD[^>]*>(?P<asd>[^<]*?)</TD>'

    def _fetch(self):
        result_list = []
        html_data = self.http.Get(self.fetch_url)
        html = html_data.decode('utf-8')
        list_by_day = util.reg_helper(html,self.reg_str_1)
        for day in list_by_day:
            date_str = util.reg_helper(day[0],self.reg_str_date)[0]
            date = datetime.strptime(date_str,"%A, %B %d, %Y ") # 'Friday, November 09, 2012 '
            info_list = util.reg_helper(day[0],self.reg_str_tbodys)
            for info in info_list:
                item_info_list = util.reg_helper(info,self.reg_str__info)
                ti = datetime.strptime(item_info_list[3],"%M:%S")
                item = track_db.TrackData.GetInstance(
                    [
                        -1,
                        self.track_type,
                        self.item_id,
                        date + timedelta(seconds=ti.second, minutes=ti.minute),
                        item_info_list[1].replace('\n\r\t','').replace('\r','').replace('\t', '').strip(),
                        item_info_list[2].replace('\n\r\t','').replace('\r','').replace('\t', '').strip(),
                        -1,
                        None
                    ]
                )
                if 'delivered' in item.description.lower():
                    item.is_ended = 1
                result_list.append(item)
        self._chk_new_items(result_list)

